// ********************************
// kooparoids.js Script
// ********************************

var MarioLives = 0;
var MarioScore = 0;
//var MarioInvincible = false;
var MarioInvincibleFade = 0;
var MarioIsDead = true;
var MarioFireFade = 0;
var MarioShield = 0;  // 0=no shields
  var MAX_SHIELD = 128;
var MarioSize = 0;  // 0=little,1=big
  var SIZE_LITTLE = 0;
  var SIZE_BIG = 1;
var GameLevel = 0;
var GameLevelMaj, GameLevelMin
var GamePlaying = false;
var LevelPlaying = false;
var MarioBulletCount;
var MAX_MARIOBULLET = 4;
var MAX_MARIOSPEED = 400;
var MarioBulletDelay;
var DEFAULT_MARIOBULLETDELAY = 8;
var SpriteArr = new Array();
var MarioSpriteNum;
SND_fireball = LoadSound("fireball.wav");
SND_fireball.setVolume(100);
SND_music_flag = LoadSound("music_flag.wav");
SND_music_gameover = LoadSound("music_gameover.wav");
SND_music_wingame = LoadSound("music_wingame.wav");
var ScoreFont = LoadFont("beakerbigmain.rfn");
var ScoreFontColor = CreateColor(255,255,255,255);
var ScoreFontAlertColor = CreateColor(255,64,64,255);
var LevelTime;
ScoreFont = LoadFont("base.rfn");
ScoreFont.setColorMask(CreateColor(0,0,0,255));
GameTopImage = LoadImage("GameTop2.png");
var WonGame = false;

var ctest_scount;
var ctest_totalsectors = 0;
var ctest_Xsectors = 0;
var ctest_Ysectors = 0;
ctest_spa = new Array();
ctest_sector_spritecount = new Array();
ctest_sector_sprite = new Array();
//var ctest_sector_width = 128;
//var ctest_sector_height = 96;
var ctest_sector_width = 144;
var ctest_sector_height = 96;
ctest_coll_raw = new Array();
ctest_coll_final = new Array();
ctest_coll_rawcount = 0;
ctest_coll_finalcount = 0;

// Define level characteristics
LevelDef = new Array();
LevelDef[1] = "Goomba:None=2";
LevelDef[2] = "Goomba:None=3";
LevelDef[3] = "Goomba:None=2,Koopa:Green=1";
LevelDef[4] = "Goomba:None=1,Koopa:Green=1,Koopa:Red=1";
LevelDef[5] = "Goomba:None=1,Koopa:Green=1,Koopa:Red=2";
LevelDef[6] = "Goomba:None=1,Koopa:Green=1,Koopa:Blue=2";
LevelDef[7] = "Goomba:None=1,Koopa:Green=1,Koopa:Red=1,Koopa:Blue=1,Koopa:Grey=1";
LevelDef[8] = "Koopa:Red=2,Koopa:Blue=2,Koopa:Grey=2";
//LevelDef[8] = "";

// Initializes game - 
function KooparoidsPlay() {
  var i, RoundCount;
  var WonLevel;
  MarioLives = 3;
  MarioScore = 0;
  GameLevel = 1;
//  GameLevel = 8;
  GamePlaying = true;
while (GamePlaying) {
  // Clear all sprites;
  SetFrameRate(25);
  SpriteArr = 5;
  SpriteArr = new Array();
  GameLevelMaj = Math.floor((GameLevel-1)/4) + 1
  GameLevelMin = GameLevel - (GameLevelMaj-1)*4
  LevelPlaying = true;
  LevelTime = 100 + 10*(GameLevel-1);
  WonLevel = false;
  MarioIsDead = false;
  SND_Music = LoadSound("mariotechno.ogg");
  SND_Music.setVolume(150);
    // Set up sectors and asteroids
    ctest_buildsectors();
    SetUpAsteroids(LevelDef[GameLevel]);
    SetUpMario();
    MarioBulletCount = 0;
    MarioBulletDelay = DEFAULT_MARIOBULLETDELAY;
    RoundCount = 0;
    SND_Music.play(true);
    while (LevelPlaying) {
//      if (!LevelPlaying) { break; }      
      PlayRound();
      // Do periodic state checks
      RoundCount++;
      if (RoundCount >= 20) { 
        RoundCount = 0;
        if (LevelTime > 0) {LevelTime--};
        // Count the bad guys - none left, mario wins!        
        if (CountBaddies() == 0) {
          WonLevel = true;
          SND_music_flag.play(false);
          LevelPlaying = false;
          //GamePlaying = false;
        }
        // Revive Mario?
        if (MarioIsDead) {
          if (SpriteArr[MarioSpriteNum].Y >= CONST_VIEW_HEIGHT-1) {
            if (MarioLives > 0) {
              SpriteArr[MarioSpriteNum].dead = true;
              MarioIsDead = false;
              SetUpMario();
              SND_Music.play(true);
            } else {
              LevelPlaying = false;
              GamePlaying = false;
              SND_music_gameover.play(false);
              var DeathSpeak = new Array;
              DeathSpeak[0] = "Mario, you are dead!  You scored " + MarioScore + " points.";
              DeathSpeak[1] = "That is impressive.  ";
              if (MarioScore < 8000) {DeathSpeak[1] = "That is somewhat acceptable.  ";}
              if (MarioScore < 5000) {DeathSpeak[1] = "That is barely acceptable.  ";}
              if (MarioScore < 3000) {DeathSpeak[1] = "That is a weak performance.  ";}
              if (MarioScore < 1000) {DeathSpeak[1] = "That is utterly pathetic.  ";}
              DeathSpeak[2] = "Good luck in your next life!  ";
              DeathSpeak[3] = " ";
	      while (AreKeysLeft()) {GetKey();};
              DeathSplash(DeathSpeak);
            }
          }
        }
      } // End of period state check section
      if (!GamePlaying) { break; }      
    }
//    if (!LevelPlaying) { break; }      
    SND_Music.stop();
    if (WonLevel) {
      while (AreKeysLeft()) {GetKey();};
      MarioScore = MarioScore + (LevelTime * GameLevel);
      ToadAdvice(GameLevel,LevelTime,(LevelTime * GameLevel));
      GameLevel++;
      if (SND_music_flag.isPlaying()) {
        SND_music_flag.stop();
      }
      if (WonGame) {
        SND_music_wingame.play(false);
        while (AreKeysLeft()) {GetKey();}
        //PlayFinale();
        var ToadSpeakAgain = new Array();
        ToadSpeakAgain[0] = "The stupid 'PlayFinale()' function ";
        ToadSpeakAgain[1] = "doesn't work, so no final cut scene ";
        ToadSpeakAgain[2] = "for you! ";
        ToadSpeakAgain[3] = " ";
        ToadSpeakAgain[4] = "Final score: " + MarioScore;
        ToadSpeakAgain[5] = " ";
        ToadSpeakAgain[6] = " ";
        ToadSplash(ToadSpeakAgain);
        GamePlaying = false;
      }
    }    
  }
};

function SetUpAsteroids(LevelDefStr) {
  var i, j, k;
  var ThingName, ThingColor, ThingQuantity
  //jdw(10,"Level definition:" + LevelDefStr);
  DefArr = LevelDefStr.split(",");
  // Clear out the sprite array
  SpriteArr = new Array();
  // Parse the sprite config string
  for (i=0;i<DefArr.length;i++) {
    // Parse a single definition
    //jdw(10,"DefArr[" + i + "]:" + DefArr[i]);
    DefInner = DefArr[i].split("=");
    ThingQuantity = DefInner[1];
    // Parse a creature name
    DefInner = DefInner[0].split(":");
    ThingName = DefInner[0];
    ThingColor = DefInner[1];
    //jdw(10,"Thing...Quan:" + ThingQuantity + ",Name:" + ThingName + ",Color:" + ThingColor);
    for (j=0;j<ThingQuantity;j++){
      MakeBigAsteroid(ThingName + ThingColor + j,ThingName,ThingColor);
    }
  }    
}

// Makes two little asteroids
function MakeSmallAsteroids(Name,BulletDir,sX,sY,sSize,sRace,sColor){
  var tempSpeed, tempDir, tempRotFace, tempRotSpeed, tempFrame, tempFrameDelay, newName, spritenum;
  // Make "top" asteroid
  spritenum = GetNextSpriteSlot(); 
  newName = "Name" + "_1";
  switch(sSize){
    case SSIZE_SMALL:
      tempSpeed = Math.floor(GetRand(SSIZE_SMALL_SPEED_MIN, SSIZE_SMALL_SPEED_MAX));
      tempRotSpeed = degreetorad(GetRand(SSIZE_SMALL_ROTATE_MIN, SSIZE_SMALL_ROTATE_MAX));
      tempFrameDelay = Math.floor(GetRand(SSIZE_SMALL_FRAMEDELAY_MIN,SSIZE_SMALL_FRAMEDELAY_MAX));
      break;
    case SSIZE_TINY:
      tempSpeed = Math.floor(GetRand(SSIZE_TINY_SPEED_MIN, SSIZE_TINY_SPEED_MAX));
      tempRotSpeed = degreetorad(GetRand(SSIZE_TINY_ROTATE_MIN, SSIZE_TINY_ROTATE_MAX));
      tempFrameDelay = Math.floor(GetRand(SSIZE_TINY_FRAMEDELAY_MIN,SSIZE_TINY_FRAMEDELAY_MAX));
      break;
    default: break;
  }
  // End of size casing...
  tempDir = Math.floor(GetRandAngle(0, 360));
  if (Math.floor(Math.random()*2) == 0) {tempRotSpeed = 0-tempRotSpeed};
  tempRotFace = degreetorad(GetRandAngle(0, 360));
  tempFrame = Math.floor(GetRand(0,2));
  SpriteArr[spritenum] = new jonboy_sprite(newName, sX, sY, tempDir, tempSpeed, tempRotFace, tempRotSpeed, MAJT_ASTEROID, sRace, sSize, sColor, tempFrame, tempFrameDelay, 2);
  // Make "bottom" asteroid
  var spritenum = GetNextSpriteSlot();   
  newName = "Name" + "_2";
  // Need to be cased for size...
  switch(sSize){
    case SSIZE_SMALL:
      tempSpeed = Math.floor(GetRand(SSIZE_SMALL_SPEED_MIN, SSIZE_SMALL_SPEED_MAX));
      tempRotSpeed = degreetorad(GetRand(SSIZE_SMALL_ROTATE_MIN, SSIZE_SMALL_ROTATE_MAX));
      tempFrameDelay = Math.floor(GetRand(SSIZE_SMALL_FRAMEDELAY_MIN,SSIZE_SMALL_FRAMEDELAY_MAX));
      break;
    case SSIZE_TINY:
      tempSpeed = Math.floor(GetRand(SSIZE_TINY_SPEED_MIN, SSIZE_TINY_SPEED_MAX));
      tempRotSpeed = degreetorad(GetRand(SSIZE_TINY_ROTATE_MIN, SSIZE_TINY_ROTATE_MAX));
      tempFrameDelay = Math.floor(GetRand(SSIZE_TINY_FRAMEDELAY_MIN,SSIZE_TINY_FRAMEDELAY_MAX));
      break;
    default: break;
  }
  // End of size casing...
  tempDir = Math.floor(GetRandAngle(0, 360));
  if (Math.floor(Math.random()*2) == 0) {tempRotSpeed = 0-tempRotSpeed};
  tempRotFace = degreetorad(GetRandAngle(0, 360));
  tempFrame = Math.floor(GetRand(0,2));
  SpriteArr[spritenum] = new jonboy_sprite(newName, sX, sY, tempDir, tempSpeed, tempRotFace, tempRotSpeed, MAJT_ASTEROID, sRace, sSize, sColor, tempFrame, tempFrameDelay, 2);
}

// Makes a big new asteroid
function MakeBigAsteroid(Name,NameType,ColorType) {
  var spritenum = GetNextSpriteSlot(); 
  var nameval, colorval;
    if (ColorType=="Blue") {colorval = SCOL_BLUE;}
    if (ColorType=="Green") {colorval = SCOL_GREEN;}
    if (ColorType=="Grey") {colorval = SCOL_GREY;}
    if (ColorType=="Red") {colorval = SCOL_RED;}
    if (NameType=="Goomba") {nameval = SRACE_GOOMBA;}
    if (NameType=="Koopa") {nameval = SRACE_KOOPA;}
    if (NameType=="Buzzy") {nameval = SRACE_BUZZY;}
    if (NameType=="Bowser") {nameval = SRACE_BOWSER;}
  var tempX, tempY, tempSpeed, tempDir, tempRotFace, tempRotSpeed, tempFrame, tempFrameDelay;
  tempX = BOARD_CENTER_X;
  tempY = BOARD_CENTER_Y;
  while (CalcDistance(tempX,tempY,BOARD_CENTER_X,BOARD_CENTER_Y) < 120) {
    tempX = Math.floor(GetRand(0,CONST_VIEW_WIDTH));
    //tempY = Math.floor(GetRand(HEAD_HEIGHT,HEAD_HEIGHT+384));
    tempY = Math.floor(GetRand(0,CONST_VIEW_HEIGHT))
  }
  tempSpeed = Math.floor(GetRand(SSIZE_BIG_SPEED_MIN, SSIZE_BIG_SPEED_MAX));
  tempDir = Math.floor(GetRandAngle(0, 360));
//  tempRotSpeed = Math.floor(GetRand(SSIZE_BIG_ROTATE_MIN, SSIZE_BIG_ROTATE_MAX));
  tempRotSpeed = degreetorad(GetRand(SSIZE_BIG_ROTATE_MIN, SSIZE_BIG_ROTATE_MAX));
  if (Math.floor(Math.random()*2) == 0) {tempRotSpeed = 0-tempRotSpeed};
//  tempRotFace = Math.floor(GetRandAngle(0, 360));
  tempRotFace = degreetorad(GetRandAngle(0, 360));
  tempFrameDelay = Math.floor(GetRand(SSIZE_BIG_FRAMEDELAY_MIN,SSIZE_BIG_FRAMEDELAY_MAX));
  tempFrame = Math.floor(GetRand(0,2));
  //jdw(10,"Making new big sprite: #" + spritenum + " " + Name + " X:" + tempX + " Y:" + tempY + " D:" + tempDir + " S:" + tempSpeed + " RF:" + tempRotFace + " RS:" + tempRotSpeed + " NV:" + nameval + " CV:" + colorval);
//  SpriteArr[spritenum] = new jonboy_sprite(Name, tempX, tempY, tempDir, tempSpeed, tempRotFace, tempRotSpeed, MAJT_ASTEROID, nameval, SSIZE_BIG, colorval);
//  SpriteArr[spritenum] = new jonboy_sprite(Name, tempX, tempY, tempDir, tempSpeed, tempRotFace, tempRotSpeed, MAJT_ASTEROID, nameval, SSIZE_BIG, colorval, tempFrame, tempFrameDelay, 2);
  SpriteArr[spritenum] = new jonboy_sprite(Name, tempX, tempY, tempDir, tempSpeed, tempRotFace, tempRotSpeed, MAJT_ASTEROID, nameval, SSIZE_BIG, colorval, tempFrame, tempFrameDelay, 2);
}

// Figures out what the next open slot is
function GetNextSpriteSlot() {
  var i;
  var NextSlot = 0;
  for (i=0;i<SpriteArr.length;i++) {
    if ( (SpriteArr[i] == undefined) || (SpriteArr[i].dead) ) {
      NextSlot = i;
      break;
    } else {
      NextSlot = i+1;
    }
  }  
  return NextSlot;
}

// Returns a random number in a range
function GetRand(Min,Max) {
  var Diff = Max-Min;
  return (Min + (Diff*Math.random()));
}

// Returns a random angle ("normallized" in the range 0-360)
function GetRandAngle(Min,Max){
  var tempAngle = GetRand(Min,Max);
  while (tempAngle<0) {
    tempAngle = tempAngle + 360;
  }
  while (tempAngle>=360) {
    tempAngle = tempAngle - 360;
  }
  return tempAngle;
}

// Calculates the distance between two points
function CalcDistance(ax,ay,bx,by) {
  return Math.sqrt( (ax-bx)*(ax-bx) + (ay-by)*(ay-by) );
}

function PlayRound(){
 
      // Force sprites to be registered in sectors
      ctest_clearsectors();
      // ctest_dumpsprites();
      ctest_scount = SpriteArr.length;
      for (j=0;j<ctest_scount;j++) {
        if (!SpriteArr[j].dead) {
          SpriteArr[j].registerinsectors(j);
        }
      }    
      //ctest_dumpsectors();
      // Reset global counters
      if (MarioBulletDelay < DEFAULT_MARIOBULLETDELAY){
        MarioBulletDelay++;
      }
      // Check each sector for collisions
      ctest_coll_rawcount = 0;
      for (j=0;j<ctest_totalsectors;j++) {
        ctest_checksector(j);
      }	
      // Remove duplicates from collision queue 
      ctest_processcollisionqueue();      
      
      // Process keyboard input
      ProcessKeyboard();
      
      // Clear video buffer, update and render each living sprite
      ClearScreen();
      for (j=0;j<ctest_scount;j++) {
        if (!SpriteArr[j].dead) {
          SpriteArr[j].update();
          SpriteArr[j].render();
        }
      }    
      // Display top of game banner
      GameTopImage.blit(0,0);
      // Display score
      ScoreFont.setColorMask(ScoreFontColor);
      ScoreFont.drawText(300 ,2, MarioScore);
      // Display level      
      ScoreFont.drawText(427 ,19, GameLevelMaj + " - " + GameLevelMin);
      // Display lives
      ScoreFont.drawText(427 ,2, MarioLives);
      // Display timer
      if (LevelTime > 20) { ScoreFont.setColorMask(ScoreFontColor); } else {
        ScoreFont.setColorMask(ScoreFontAlertColor);
      }
      ScoreFont.drawText(300 ,19, LevelTime);
      FlipScreen();
 
}

function ctest_clearsectors() {
  var i;
  for (i=0;i<ctest_totalsectors;i++) {
    ctest_sector_spritecount[i] = 0;
  }
}

// Process raw collision queue - spit out final queue
// Notify each sprite
function ctest_processcollisionqueue() {
  ctest_coll_finalcount = 0;
  ctest_coll_raw.sort();
  var i;
  var lastcoll = "";
  for (i=0;i<ctest_coll_rawcount;i++) {
    if (lastcoll == ctest_coll_raw[i]) {
      // Ignore duplicate collisions
      //jdw(10, "Ignoring duplicate collision!");
    } else {
      ctest_coll_final[ctest_coll_finalcount] = ctest_coll_raw[i];
      ctest_coll_finalcount++;
      lastcoll = ctest_coll_raw[i];    
    }  
  }
  // Okay, now issue collisions to the various sprites
  for (i=0;i<ctest_coll_finalcount;i++) {
    collarr = ctest_coll_final[i].split("|");
    //ctest_spa[collarr[0]].direction_set(bouncedir(ctest_spa[collarr[0]].direction));
    //ctest_spa[collarr[1]].direction_set(bouncedir(ctest_spa[collarr[1]].direction));
    //jdw(10,"Issuing collision to " + collarr[0] + " and " + collarr[1]);
    SpriteArr[collarr[0]].collide(collarr[1]);
    SpriteArr[collarr[1]].collide(collarr[0]);
  }  
}

function ctest_buildsectors() {
  ctest_Xsectors = CONST_VIEW_WIDTH/ctest_sector_width;
  ctest_Ysectors = CONST_VIEW_HEIGHT/ctest_sector_height;
  ctest_totalsectors = ctest_Xsectors * ctest_Ysectors;
  //jdw(6,"Need to create " + ctest_totalsectors + " new sectors.");
  var i;
  for (i=0;i<ctest_totalsectors;i++) {
    ctest_sector_sprite[i] = new Array();
  }
  //jdw(6,"Created " + ctest_totalsectors + " new sectors OK.");
}

// Called to check sprite collisions in this sector
function ctest_checksector(sectnum) { 
  var i,j;
  //jdw(7,"Checking for collisions in sector " + sectnum + ".");
  // Check for collisions among all sprites in the sector
  for (i=0;i<ctest_sector_spritecount[sectnum]-1;i++) {
    for (j=i+1;j<ctest_sector_spritecount[sectnum];j++){
      ctest_comparisonsmade = ctest_comparisonsmade + 1;
      if (sprites_overlap_rect(ctest_sector_sprite[sectnum][i],ctest_sector_sprite[sectnum][j])) {
        //jdw(10,"Detected collision between sector sprites " + i + " and " + j + ", registered as raw #" + ctest_coll_rawcount);
//        ctest_collisionsdetected = ctest_collisionsdetected + 1;
	ctest_coll_raw[ctest_coll_rawcount] = ctest_sector_sprite[sectnum][i] + "|" + ctest_sector_sprite[sectnum][j]	
	ctest_coll_rawcount++;
      }
    }      
  }
}

// Called to perform a RECTANGULAR collision test with two sprites
function sprites_overlap_rect(S1,S2) {
  // Ignore collisions between sprites of same major type
  if (SpriteArr[S1].majortype == SpriteArr[S2].majortype) {
    return false;
  } else {
    if ((SpriteArr[S1].rectX1abs > SpriteArr[S2].rectX2abs) 
	  || (SpriteArr[S2].rectX1abs > SpriteArr[S1].rectX2abs) 
	  || (SpriteArr[S1].rectY1abs > SpriteArr[S2].rectY2abs) 
	  || (SpriteArr[S2].rectY1abs > SpriteArr[S1].rectY2abs)) {
      return false;
    } else {
      return true;
    }
  }
}

function SetUpMario(){
  var spritenum = GetNextSpriteSlot(); 
  SpriteArr[spritenum] = new jonboy_sprite("Mario", BOARD_CENTER_X, BOARD_CENTER_Y, 0, 0, 0, 0, MAJT_SHIP, SRACE_MARIO, SSIZE_BIG, "", 0, 12, 0);
  MarioSpriteNum = spritenum;
}

function ProcessKeyboard(){
  if (!MarioIsDead){
      if (IsKeyPressed(KEY_Q)) {
        GamePlaying = false;
      }
      if (IsKeyPressed(KEY_LEFT)) {
        SpriteArr[MarioSpriteNum].rotateface_subtract(.12);
      }
      if (IsKeyPressed(KEY_RIGHT)) {
        SpriteArr[MarioSpriteNum].rotateface_add(.12); 
      }
      if (IsKeyPressed(KEY_UP)) {
        SpriteArr[MarioSpriteNum].shove(SpriteArr[MarioSpriteNum].rotateface,12)
      }
      if (IsKeyPressed(KEY_SPACE)) {
        MarioFireFade = 4; 
        MarioFireBullet();
      }
  }
}

function MarioFireBullet(){
  if ((MarioBulletCount < MAX_MARIOBULLET) && (MarioBulletDelay == DEFAULT_MARIOBULLETDELAY)) {
    if (SND_fireball.isPlaying()) { SND_fireball.stop(); }
    MarioBulletDelay = 0;
    var spritenum = GetNextSpriteSlot(); 
    SpriteArr[spritenum] = new jonboy_sprite("MarioBullet" + spritenum, SpriteArr[MarioSpriteNum].X, SpriteArr[MarioSpriteNum].Y, SpriteArr[MarioSpriteNum].rotateface, 480, 0, 0, MAJT_BULLET, SRACE_MARIO, SSIZE_BIG, "", 0, 2, 4);  
    SND_fireball.play(false);
    MarioBulletCount++;
  }
}


// Dumps a list of all sectors to the debug log
function ctest_dumpsectors(){
  var i,j;
  for (i=0;i<ctest_totalsectors;i++){
    jdw(9, "Sector #" + i + ": " + ctest_sector_spritecount[i] + " sprites total");
    for (j=0;j<ctest_sector_spritecount[i];j++){
      jdw(10, "...SectorSprite #" + j + " is really Sprite #" + ctest_sector_sprite[i][j] + "");
    }
  }
}

// Dumps a list of all sprites to the debug log
function ctest_dumpsprites(){
  var i;
  for (i=0;i<ctest_scount;i++){
    jdw(10,"Sprite #" + i + ": " + ctest_spa[i].ID + " (" + ctest_spa[i].name + ")" );
    jdw(10,"...direction:" + ctest_spa[i].direction + "  speed:" + ctest_spa[i].speed  + "  X:" + ctest_spa[i].X  + "  Y:" + ctest_spa[i].Y );
    jdw(10,"...rectX1abs:" + ctest_spa[i].rectX1abs + "  rectX2abs:" + ctest_spa[i].rectX2abs  + "  rectY1abs:" + ctest_spa[i].rectY1abs  + "  rectY2abs:" + ctest_spa[i].rectY2abs );
  }
}

// Counts the number of asteroids still "alive"
function CountBaddies(){
  var j, mycount=0;  
      for (j=0;j<ctest_scount;j++) {
        if ((!SpriteArr[j].dead) && (SpriteArr[j].majortype == MAJT_ASTEROID)) {
          mycount++;
        }
      } 
    return mycount;   
}

function ToadAdvice(LevelDone,TimeRemain,TimeBonus) {
      ToadSpeak = new Array();
      ToadSpeak[0] = "Good job Mario! ";
      ToadSpeak[1] = "Time Bonus = (" + TimeRemain + " ticks) x (level " + LevelDone + ") = " + TimeBonus;
      ToadSpeak[2] = " ";
      switch(GameLevel) {
        case 1: 
		ToadSpeak[2] = "Sorry about all the Goombas. "; 
		ToadSpeak[3] = "I guess the Mushroom Kingdom "; 
		ToadSpeak[4] = "drug rehab program needs some work. "; 
		ToadSpeak[5] = " ";
		break;
        case 2: 
		ToadSpeak[2] = "Watch out for the Koopas! "; 
		ToadSpeak[3] = "Their shells are fireproof, so "; 
		ToadSpeak[4] = "you need to hit them somewhere else. "; 
		ToadSpeak[5] = " ";
		break;
        case 3: 
		ToadSpeak[2] = "Red Koopas will hide in "; 
		ToadSpeak[3] = "their shells if frightened, "; 
		ToadSpeak[4] = "so shoot carefully! "; 
		ToadSpeak[5] = " ";
		break;
        case 4: 
		ToadSpeak[2] = "Hopefully in a future version "; 
		ToadSpeak[3] = "some witty cut scene will "; 
		ToadSpeak[4] = "pop up here, but not yet. "; 
		ToadSpeak[5] = " ";
		break;
        case 5: 
		ToadSpeak[2] = "Remember how if you hit "; 
		ToadSpeak[3] = "the shell of a Red or Green "; 
		ToadSpeak[4] = "Koopa, it would at least change "; 
		ToadSpeak[5] = "direction?  Not so with Blue Koopas! "; 
		ToadSpeak[6] = " ";
		break;
        case 6: 
		ToadSpeak[2] = "Grey Koopas not only "; 
		ToadSpeak[3] = "plow right through shots, "; 
		ToadSpeak[4] = "but also hide in their shells. "; 
		ToadSpeak[5] = " ";
		break;
        case 7: 
		ToadSpeak[2] = "Hey - you're getting close! "; 
		ToadSpeak[3] = "This is the LAST LEVEL..."; 
		ToadSpeak[4] = "...at least for now."; 
		ToadSpeak[5] = " ";
		break;
        case 8: 
                WonGame = true;
		ToadSpeak[2] = "You WON the game! "; 
		ToadSpeak[3] = "(I hope you didn't cheat.) "; 
		ToadSpeak[4] = " ";
		break;
      }      
      ToadSplash(ToadSpeak);    
}